package cn.iocoder.yudao.module.shop.controller.admin.order;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.shop.controller.admin.item.vo.ShopItemRespVO;
import cn.iocoder.yudao.module.shop.dal.dataobject.order.ShopOrderItemDO;
import cn.iocoder.yudao.module.shop.service.item.ShopItemService;
import cn.iocoder.yudao.module.shop.service.order.ShopOrderItemService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import kotlin.collections.EmptyList;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.io.IOException;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.shop.controller.admin.order.vo.*;
import cn.iocoder.yudao.module.shop.dal.dataobject.order.ShopOrderDO;
import cn.iocoder.yudao.module.shop.convert.order.ShopOrderConvert;
import cn.iocoder.yudao.module.shop.service.order.ShopOrderService;

@Tag(name = "管理后台 - 店内消耗订单")
@RestController
@RequestMapping("/shop/order")
@Validated

public class ShopOrderController {

    @Resource
    private ShopOrderService orderService;

    @Resource
    private MemberUserApi memberUserApi;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private ShopOrderItemService shopOrderItemService;

    @Resource
    private ShopItemService shopItemService;

    @PostMapping("/create")
    @Operation(summary = "创建店内消耗订单")
    @PreAuthorize("@ss.hasPermission('shop:order:create')")
    public CommonResult<Long> createOrder(@Valid @RequestBody ShopOrderCreateReqVO createReqVO) {
        return success(orderService.createOrder(createReqVO));
    }

    @PostMapping("/check")
    @Operation(summary = "核销店内订单")
    @PreAuthorize("@ss.hasPermission('shop:order:update')")
    public CommonResult<Boolean> check(@Valid @RequestBody ShopOrderCheckReqVO checkReqVO) {
        return success(orderService.check(checkReqVO));
    }

    @GetMapping("/rollback")
    @Operation(summary = "核销错误，order 退回")
    @PreAuthorize("@ss.hasPermission('shop:order:update')")
    public CommonResult<Boolean> rollback(@RequestParam("id") Long id) {
        return success(orderService.rollback(id));
    }

    @PutMapping("/update")
    @Operation(summary = "更新店内消耗订单")
    @PreAuthorize("@ss.hasPermission('shop:order:update')")
    public CommonResult<Boolean> updateOrder(@Valid @RequestBody ShopOrderUpdateReqVO updateReqVO) {
        orderService.updateOrder(updateReqVO);
        return success(true);
    }

    @GetMapping("/cancel")
    @Operation(summary = "取消店内订单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('shop:order:update')")
    public CommonResult<Boolean> cancelOrder(@RequestParam("id") Long id) {
        orderService.cancelOrder(id);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除店内消耗订单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('shop:order:delete')")
    public CommonResult<Boolean> deleteOrder(@RequestParam("id") Long id) {
        orderService.deleteOrder(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得店内消耗订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('shop:order:query')")
    public CommonResult<ShopOrderRespVO> getOrder(@RequestParam("id") Long id) {
        ShopOrderDO order = orderService.getOrder(id);
        MemberUserRespDTO memberUserRespDTO = memberUserApi.getUser(order.getMemberId());
        ShopOrderRespVO shopOrderRespVO = ShopOrderConvert.INSTANCE.convert(order, memberUserRespDTO);
        return success(shopOrderRespVO);
    }

    @GetMapping("/nocheck")
    @Operation(summary = "获得店内消耗订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('shop:order:query')")
    public CommonResult<List<ShopOrderRespVO>> getNoCheckList(){
        LocalDate today = LocalDate.now();
        LocalDateTime zeroToday = LocalDateTime.of(today, LocalTime.MIN);

        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser == null){
            return success(new ArrayList<>());
        }

        AdminUserRespDTO user = adminUserApi.getUser(loginUser.getId());
        if(user == null){
            return success(new ArrayList<>());
        }

        List<ShopOrderDO> orderList = orderService.getNoCheckOrderList(zeroToday, user.getTenantId());

        if(orderList.size() == 0){
            return success(new ArrayList<>());
        }

        // 查询艾灸师
        Set<Long> userIds = convertSet(orderList, ShopOrderDO::getUserId);
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(userIds);

        // 查询用户信息
        Set<Long> memberIds = convertSet(orderList, ShopOrderDO::getMemberId);
        Map<Long, MemberUserRespDTO> memberMap = memberUserApi.getUserMap(memberIds);

        List<ShopOrderItemDO> shopOrderItemDOS = shopOrderItemService.getShopOrderItemListByOrderId(convertSet(orderList, ShopOrderDO::getId));

        //查询店内项目
        Set<Long> itemIds = convertSet(shopOrderItemDOS, ShopOrderItemDO::getOptItemId);
        Map<Long, ShopItemRespVO> shopItemRespVOMap = shopItemService.getItemMap(itemIds);

        return success(ShopOrderConvert.INSTANCE.convertList(orderList, shopOrderItemDOS, shopItemRespVOMap, memberMap, userMap));
    }

    @GetMapping("/list")
    @Operation(summary = "获得店内消耗订单列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('shop:order:query')")
    public CommonResult<List<ShopOrderRespVO>> getOrderList(@RequestParam("ids")  Collection<Long> ids) {
        List<ShopOrderDO> list = orderService.getOrderList(ids);
        return success(ShopOrderConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得店内消耗订单分页")
    @PreAuthorize("@ss.hasPermission('shop:order:query')")
    public CommonResult<PageResult<ShopOrderRespVO>> getOrderPage(@Valid ShopOrderPageReqVO pageVO) {
        PageResult<ShopOrderDO> pageResult = orderService.getOrderPage(pageVO);
        if(CollUtil.isEmpty(pageResult.getList())){
            return success(PageResult.empty());
        }

        // 查询艾灸师
        Set<Long> userIds = convertSet(pageResult.getList(), ShopOrderDO::getUserId);
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(userIds);

        // 查询用户信息
        Set<Long> memberIds = convertSet(pageResult.getList(), ShopOrderDO::getMemberId);
        Map<Long, MemberUserRespDTO> memberMap = memberUserApi.getUserMap(memberIds);

        List<ShopOrderItemDO> shopOrderItemDOS = shopOrderItemService.getShopOrderItemListByOrderId(convertSet(pageResult.getList(), ShopOrderDO::getId));

        //查询店内项目
        Set<Long> itemIds = convertSet(shopOrderItemDOS, ShopOrderItemDO::getOptItemId);
        Map<Long, ShopItemRespVO> shopItemRespVOMap = shopItemService.getItemMap(itemIds);

        return success(ShopOrderConvert.INSTANCE.convertPage(pageResult, shopOrderItemDOS, shopItemRespVOMap, memberMap, userMap));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出店内消耗订单 Excel")
    @PreAuthorize("@ss.hasPermission('shop:order:export')")
    @OperateLog(type = EXPORT)
    public void exportOrderExcel(@Valid ShopOrderExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<ShopOrderDO> list = orderService.getOrderList(exportReqVO);
        // 导出 Excel
        List<ShopOrderExcelVO> datas = ShopOrderConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "店内消耗订单.xls", "数据", ShopOrderExcelVO.class, datas);
    }

}
